import { Breadcrumb, Select, Input } from 'antd'
import { Table, Popconfirm, Button, Modal, Form, Switch, Upload, DatePicker, message, Pagination } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import React from 'react';
import { useState } from 'react';
const { Option } = Select;
import '../assets/styles/Yseckill.less'

import { instance } from '../../../api/request'

import { history } from 'umi'

const { RangePicker } = DatePicker;

const { Search } = Input;
export default function seckill() {
    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    )
    const [dataSource, setdataSource] = useState([])
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isModalVisible1, setIsModalVisible1] = useState(false);
    const [previewVisible, setpreviewVisible] = useState(false)
    const [previewImage, setpreviewImage] = useState('')
    const [previewTitle, setpreviewTitle] = useState('')
    const [fileList, setfileList] = useState([])
    const [checked, setchecked] = useState(false)
    const [img, setimg] = useState([])
    const [current, setcurrent] = useState(1)
    const [pageSize, setpageSize] = useState(1)
    const [total, settotal] = useState(0)
    const [eachRow, seteachRow] = useState({ id: 1 })
    const paginations = {
        current: current,
        pageSize: pageSize,
        total: total,
        onChange: (current: any, size: any) => changepage(current, size)
    }
    React.useEffect((): any => {
        changepage(1, 3)
        findData()
    }, [])
    //查询全部数据条数
    async function findData() {
        const res = await instance.get('/seckilltime/findAll')
       
        settotal(res.data.length)

    }
    //分页
    async function changepage(current: any, pageSize: any) {
        const obj = { page: current, pageSize: pageSize }
        const res = await instance.post('/seckilltime/limit', obj)
        
        var arr: any = []
        if (res.data.length > 0) {

            res.data.forEach((ite: any) => {
                const img1 = ite.img.split('#').filter(function (s: any) {
                    return s && s.trim();
                });

                if (ite.state == '1') {
                    const obj = {
                        id: ite.id,
                        name: ite.name,
                        times: ite.times,
                        state: true,
                        img: img1,
                        createdAt: ite.createdAt
                    }
                    arr.push(obj)
                   
                } else {
                    const obj = {
                        id: ite.id,
                        name: ite.name,
                        times: ite.times,
                        state: false,
                        img: img1,
                        createdAt: ite.createdAt
                    }
                    arr.push(obj)
                }
                
            })
            arr.forEach((item: any, index: any) => {
                item.key = index
            })
            setdataSource(arr)
        } else {
            setdataSource(res.data)
        }


        setpageSize(pageSize)
        setcurrent(current)
    }
    
    //删除
    async function del(record: any) {
         const res=await instance.post('/api1/seckilltime/del',record)
      
        changepage(1, 3)
    }

    function showModal(record: any) {
        seteachRow(record)
        setIsModalVisible(true);
    }

    function handleCancel2() {
        setIsModalVisible(false)
    }

    function handleCancel1() {
        setIsModalVisible1(false)
    }
    //编辑
    async function onFinish(e: any) {
        const times = e.times[0].format('YYYY-MM-DD HH:mm:ss') + '-' + e.times[1].format('YYYY-MM-DD HH:mm:ss')
        if (checked == true) {
            var state = '1'
        } else {
            state = '0'
        }    
        console.log(checked);
        console.log(state);
        
        const obj = {
            id: eachRow.id,
            name: e.name,
            times: times,
            state: state
        }
       const res=await instance.post('/seckilltime/update',obj)
        changepage(1, 3)
        setIsModalVisible(false);
    }
    //编辑改变状态
    function updateChange(e: any) {
        const state=e
    }
    //添加
    async function onFinish1(e: any) {
        const times = e.times[0].format('YYYY-MM-DD HH:mm:ss') + '-' + e.times[1].format('YYYY-MM-DD HH:mm:ss')
        const formData = new FormData();
        fileList.forEach((file: any) => {
            formData.append('file', file.originFileObj);
        });
        formData.append('times', times);
        formData.append('name', e.name);

        if (checked == true) {
            var state = '1'
        } else {
            state = '0'
        }
        formData.append('state', state)
        const res = await instance.post('/seckilltime', formData)
        console.log(res);
        
        setIsModalVisible1(false);
    }

    //改变状态
    function onChanges(checked: any) {
        console.log(checked, 99999);

    }
    //添加改变状态
    function onChanges1(e: any) {
        setchecked(!e)
    }


    function handleCancel() {
        setpreviewVisible(false)
    }
    function handleChange({ fileList }: any) {
        setfileList(fileList)
    }
    //添加商品种类
    function add(record:any){
      
        history.push({
            pathname: '/seckillAdd',
            query:record,
        })
        
    }
    const columns: any = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',

        },
        {
            title: '秒杀名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '秒杀时段',
            dataIndex: 'times',
            key: 'times',
        },
        {
            title: '轮播图',
            dataIndex: 'img',
            render: (_: any, record: any) => {
                return <>
                    <div style={{ display: 'flex' }}>
                        {
                            record.img.map((item: any, keys: any) => {
                                return <div key={keys} >
                                    <img style={{ width: '4rem', height: '4rem', marginRight: '0.5rem' }} src={item} />
                                </div>

                            })

                        }
                    </div>
                </>
            }

        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
        },
        {
            title: '状态',
            key: 'state',
            render: (_: any, record: any) => {
                return <>
                    <Switch defaultChecked checked={record.state?true:false} onChange={(e) => onChanges(e)} />
                </>
            }
        },
        {
            title: '操作',
            key: '操作',
            render: (_: any, record: any) => {
                return <>
                    <Popconfirm title="您确定要删除吗?" onConfirm={() => del(record)}>
                        <Button type="primary">删除</Button>
                    </Popconfirm>
                    <Button type="primary" onClick={() => showModal(record)}>编辑</Button>
                    <Modal title="编辑" visible={isModalVisible} onCancel={() => handleCancel2()} footer={[]}>
                        <Form name="basic" onFinish={(e) => onFinish(e)}>
                            <Form.Item label="秒杀名称" name="name">
                                <Input />
                            </Form.Item>
                            <Form.Item label="秒杀时间" name="times">
                                <RangePicker />
                            </Form.Item>
                            <Form.Item label="状态" valuePropName="checked">
                                <Switch defaultChecked onChange={(e) => updateChange(e)} />
                            </Form.Item>
                            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                                <Button type="primary" htmlType="submit">
                                    编辑
                                </Button>
                            </Form.Item>
                        </Form>
                    </Modal>
                    <Button type="primary" onClick={()=>add(record)}> 添加商品</Button>
                 
                </>
            }


        },
    ]
    return (

        <div className="Yseckill">

            <div className="top">
                <Breadcrumb>
                    <Breadcrumb.Item>主页</Breadcrumb.Item>
                    <Breadcrumb.Item>营销</Breadcrumb.Item>
                    <Breadcrumb.Item>
                        <a href="/seckill">秒杀管理</a>
                    </Breadcrumb.Item>
                    <Breadcrumb.Item>
                        <a href="/seckillAdd" className="skeill">添加商品</a>
                    </Breadcrumb.Item>
                </Breadcrumb>
            </div>
            <div className="bottom">
                <div className="searchbox">
                    <div className="show">
                        <span>是否显示</span>
                        <Select defaultValue="请选择" style={{ width: 120 }} >
                            <Option value="1">关闭</Option>
                            <Option value="2">开启</Option>
                        </Select>
                    </div>
                    <div className="searchName">
                        <div className="secname">秒杀名称</div>
                        <Search placeholder="请输入秒杀名称" enterButton />
                    </div>
                </div>
                <button className="add" onClick={() => setIsModalVisible1(true)}>添加商品</button>
                <Modal title="添加商品" visible={isModalVisible1} onCancel={() => handleCancel1()} footer={[]}>
                    <Form onFinish={(e) => onFinish1(e)}>
                        <Form.Item label="秒杀名称" name="name">
                            <Input />
                        </Form.Item>
                        <Form.Item label="时间范围" name="times">
                            <RangePicker />
                        </Form.Item>
                        <Form.Item
                            label="商品主图"
                        >
                            <Upload
                                listType="picture-card"
                                fileList={fileList}
                                // onPreview={handlePreview}
                                onChange={handleChange}
                            >
                                {fileList.length >= 4 ? null : uploadButton}
                            </Upload>
                            <Modal
                                visible={previewVisible}
                                title={previewTitle}
                                footer={null}
                                onCancel={handleCancel}
                            >
                                <img alt="example" style={{ width: '100%' }} src={previewImage} />
                            </Modal>
                        </Form.Item>
                        <Form.Item label="状态" valuePropName="checked">
                            <Switch defaultChecked onChange={(e) => onChanges1(e)} />
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit">
                                添加秒杀商品
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
                <Table dataSource={dataSource} columns={columns} pagination={paginations}></Table>

            </div>
        </div>
    )
}


